﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections;
using System.Reflection;
using System.IO;
using ZebraCoreLib.Framework;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace Web.ZebraUIControls
{
    public enum TemplatePart
    {
        Header,
        Content,
        Footer,
        Script,
        ListItem,
        DetailsHeader,
        DetailsListItem,
        DetailsFooter,
        StockStatusSelector = 100,
        TimeSelector = 101,
        OrderStatusSelector = 102

    }
    public abstract class ZebraBasControls
    {
        //模板文件存放路径
        protected string templatePath = @"\App_Themes\Default\ControlsTemplate\";
        protected bool IsDesignMode { get { return System.Web.HttpContext.Current == null; } }
        private static Hashtable templateCache = new Hashtable();

        public HtmlHelper html = null;

        public  Type BizObjectType { get; set; }


        protected string HelpInfo { get; set; }

        protected StringBuilder ControlSricpts {get;set;}

        protected string BlackSpace { get; set; }
        /// <summary>
        /// 该函数指定如何绘制控件
        /// </summary>
        /// <param name="writer"></param>
        public virtual void RenderControl(HtmlTextWriter writer)
        {
             RenderControlFromTemplate(writer);
        }

        /// <summary>
        /// 从模板绘制控件
        /// </summary>
        /// <param name="writer"></param>
        protected void RenderControlFromTemplate(HtmlTextWriter writer)
        {
            RenderControlFromTemplate(writer, TemplatePart.Content,null,null);
        }

        protected void RenderControlFromTemplate(HtmlTextWriter writer,TemplatePart part)
        {
            RenderControlFromTemplate(writer, part, null,null);

        }
        protected void RenderControlFromTemplate(HtmlTextWriter writer, ZebraFieldAttribute fieldAttribure)
        {
            RenderControlFromTemplate(writer, TemplatePart.Content, fieldAttribure,null);
        }
        protected void RenderControlFromTemplate(HtmlTextWriter writer, TemplatePart part, ZebraFieldAttribute fieldAttribure)
        {
            RenderControlFromTemplate(writer, part, fieldAttribure, null);
        }
        
        protected void RenderControlFromUserControls(object bizService,string userControlFileName,TemplatePart part)
        {
            if(string.IsNullOrEmpty(userControlFileName))
                userControlFileName=this.GetType().ToString();
            string pathPath = userControlFileName + "."+ part.ToString()+".ascx";

             HtmlHelperExtented.RenderUserControls(html, pathPath, bizService);
        } 

        protected void RenderControlFromTemplate(HtmlTextWriter writer, TemplatePart part, ZebraFieldAttribute fieldAttribure, Hashtable DictionaryData)
        {
            string template = GetTemplate(part);

            bool continueFlag=true;
            //替换关键字
            if (continueFlag && DictionaryData != null && DictionaryData != null)
            {
                foreach (DictionaryEntry entry in DictionaryData)
                {
                    template = template.Replace("{" + entry.Key.ToString() + "}", entry.Value == null ? "" : entry.Value.ToString());
                    //if (template.IndexOf('{') == -1)
                    //{
                    //    continueFlag = false;
                    //    break;
                    //}

                }

            }
            //替换字段的属性
            if (continueFlag && fieldAttribure != null)
            {
                PropertyInfo[] properties = fieldAttribure.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                foreach (PropertyInfo property in properties)
                {
                    if (property.PropertyType == typeof(string) || property.PropertyType == typeof(bool) || property.PropertyType == typeof(int))
                    {
                        //替换模板文件
                        string propertyValue = property.GetValue(fieldAttribure, null) == null ? "" : property.GetValue(fieldAttribure, null).ToString();
                        template = template.Replace("{" + property.Name + "}", propertyValue);

                        //读取控件的脚本文件
                        if (!string.IsNullOrEmpty(propertyValue) && !propertyValue.Equals("false", StringComparison.OrdinalIgnoreCase))
                        {
                            string scriptTemplate = GetTemplate(TemplatePart.Script, property.Name);
                            if (string.IsNullOrEmpty(scriptTemplate))
                                continue;

                            foreach (PropertyInfo p in properties)
                            {
                                string pv = p.GetValue(fieldAttribure, null) == null ? "" : p.GetValue(fieldAttribure, null).ToString();
                                scriptTemplate = scriptTemplate.Replace("{" + p.Name + "}", pv);
                            }
                            AppendScript(scriptTemplate);

                        }
                    }
                }
                // writer.Write(template);
            }

            //替换本身的属性
            if (continueFlag)
            {
                PropertyInfo[] properties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                foreach (PropertyInfo property in properties)
                {
                    if (property.PropertyType == typeof(string) || property.PropertyType.IsEnum ||  property.PropertyType == typeof(int)  )
                    {
                        string propertyValue = property.GetValue(this, null) == null ? "" : property.GetValue(this, null).ToString();
                        template = template.Replace("{" + property.Name + "}", propertyValue);
                        if (template.IndexOf('{') == -1)
                        {
                            continueFlag = false;
                            break;
                        }
                    }
                }
            }

    

            writer.Write(template);

        }


        /// <summary>
        /// 从模板绘制控件
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="DictionaryData">key-value，表示模板要处理的特殊内容</param>
        //protected void RenderControlFromTemplate(HtmlTextWriter writer, Hashtable DictionaryData)
        //{
        //    string template = GetTemplate();
        //    PropertyInfo[] properties = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
        //    foreach (PropertyInfo property in properties)
        //    {
        //        if (property.PropertyType == typeof(string) || property.PropertyType == typeof(bool) || property.PropertyType == typeof(int))
        //        {
        //            string propertyValue = property.GetValue(this, null) == null ? "" : property.GetValue(this, null).ToString();
        //            //if (property.Name == "Title")
        //            //    propertyValue += GetHelpInfo();
        //            if (property.Name.Equals("ReadOnly", StringComparison.OrdinalIgnoreCase))
        //                if (propertyValue.Equals("True", StringComparison.OrdinalIgnoreCase))
        //                    template = template.Replace("{" + property.Name + "}", "readonly=\"readonly\"");
        //                else
        //                    template = template.Replace("{" + property.Name + "}", "");
        //            else
        //                template = template.Replace("{" + property.Name + "}", propertyValue);
        //        }
        //    }
        //    if (DictionaryData != null && DictionaryData != null)
        //    {
        //        foreach (DictionaryEntry entry in DictionaryData)
        //        {
        //            template = template.Replace("{" + entry.Key.ToString() + "}", entry.Value == null ? "" : entry.Value.ToString());
        //        }
        //    }

        //    writer.Write(template);

        //}

        protected void AppendScript(string script)
        {
            if (ControlSricpts == null)
                ControlSricpts = new StringBuilder();
            ControlSricpts.AppendLine(script);
        
        }

        public string RenderControlScript()
        {
            string js="";
            if (ControlSricpts != null)
                js = ControlSricpts.ToString();
            return js;

        }

        /// <summary>
        /// 获取模板数据
        /// </summary>
        /// <returns></returns>
        protected string GetTemplate()
        {
            return GetTemplate(TemplatePart.Content);
        }
        protected string GetTemplate(TemplatePart part)
        {
            return GetTemplate(part, "");
        }

       
        /// <summary>
        /// 获取模板数据
        /// </summary>
        /// <returns></returns>
        protected string GetTemplate(TemplatePart part,string ScriptName)
        {
            string fileName = "";
            try
            {
                string templateKey = this.GetType().Name;
                if (part == TemplatePart.Header || part == TemplatePart.Footer || part == TemplatePart.ListItem ||
                     part == TemplatePart.StockStatusSelector || part == TemplatePart.TimeSelector || part == TemplatePart.OrderStatusSelector
                    )
                    templateKey = this.GetType().Name + "." + part.ToString();

                if (part == TemplatePart.Script)
                {
                    templateKey = templateKey + "." + ScriptName;
                    fileName = templatePath + templateKey + ".js";
                }
                else
                {
                    fileName = templatePath + templateKey + ".skin";
                }
                //启用模板缓存，加快性能
                if (System.Web.HttpContext.Current.Cache[templateKey] == null)
                {

                    fileName = AppDomain.CurrentDomain.BaseDirectory + fileName;
                    using (StreamReader reader = new StreamReader(fileName))
                    {
                        string cacheTemplate = reader.ReadToEnd();
                        System.Web.HttpContext.Current.Cache[templateKey] = cacheTemplate;
                    }
                }

                return System.Web.HttpContext.Current.Cache[templateKey].ToString();
                   
            }
            catch
            {
                return null;
            }
        }

        protected string Decode(string sourceString)
        {
            return System.Web.HttpUtility.HtmlDecode(sourceString);
        }

     
    }
}
